package com.example.swimfish;

import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;

@ClientEndpoint
public class WebSocketClient {
    private Session session;
    private final URI endpointURI;
    private final MessageHandler messageHandler;

    public WebSocketClient(URI endpointURI, MessageHandler messageHandler) {
        this.endpointURI = endpointURI;
        this.messageHandler = messageHandler;
    }

    public void connect() {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("Connected to server: " + session.getId());
    }

//    @OnMessage
//    public void onMessage(String message) {
//        if (messageHandler != null) {
//            messageHandler.handleMessage(message);
//        }
//    }
    @OnMessage
    public void onMessage(String message) {
        if (messageHandler != null) {
            // 确保消息处理也在FX线程上执行
            javafx.application.Platform.runLater(() -> {
                messageHandler.handleMessage(message);
            });
        }
    }
    public void sendMessage(String message) {
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface MessageHandler {
        void handleMessage(String message);
    }
}